<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Area;
use App\Http\Controllers\BaseController;
use App\Models\ChinaArea;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Models\Administrator;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Hash;

class AreaController extends BaseController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Area(['admin']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('city');
            $grid->column('fullname');
            $grid->column('phone');
            $grid->column('admin.username','账号');
            $grid->column('status')->using(['正常','隐藏'])->label(['info','default']);
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->quickSearch(['city','fullname','phone','admin.username']);
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Area(['admin']), function (Form $form) {
            $form->display('id');
            $form->hidden('admin_id')->default(0);
            $form->distpicker(['p_code' => '选择省','code'=> '选择市'],'所属城市')->validator(function ($value){
                $rules = $attributes = [];
                $messages = ['p_code'=>'省份','code'=>'市'];
                if (!$fieldRules = $this->getRules()) {
                    return false;
                }
                foreach ($this->column as $column) {
                    if (!Arr::has($value, $column)) {
                        continue;
                    }
                    $input[$column] = Arr::get($value, $column);
                    $rules[$column] = $fieldRules;
                    $attributes[$column] = $this->label.$messages[$column];
                }
                return \validator($value, $rules, $this->getValidationMessages(), $attributes);
            })->required();
            $form->text('fullname')->required();
            $form->text('phone')->required();
            $form->hidden('name');
            $form->hidden('p_name');
            $form->hidden('city');
            $id = $form->getKey();
            $model = $form->model();
            $username = $model->admin?$model->admin->username:'';
            $form->text('username','账号')->attribute(['autocomplete'=>'off'])->value($username)->required();
            $password = $form->password('password','密码')
                ->rules(['alpha_num'],['alpha_num'=>'密码必须为大小写字母或者数字'])
                ->minLength(6,'最少6位字符')
                ->maxLength(15,'最长15位字符')
                ->attribute(['autocomplete'=>'new-password']);
            if($id){
                $password->help("不修改密码,请留空");
            }else{
                $password->required();
            }
            $form->radio('status')->options(['正常','隐藏'])->default(0);
            $form->saving(function (Form $form){
                $code = $form->code;
                $p_code = $form->p_code;
                if (!$code){
                    return $form->response()->error("请先选择城市!");
                }
                if($form->isCreating()){
                    $exit = \App\Models\Area::query()->where("code",$code)->exists();
                    if($exit){
                        return $form->response()->error("此城市已存在!");
                    }
                }
                if($form->isEditing()){
                    $exit = \App\Models\Area::query()->where("id","<>",$form->getKey())->where("code",$code)->exists();
                    if($exit){
                        return $form->response()->error("此城市已存在!");
                    }
                }
                $area = ChinaArea::query()->whereIn("code",[$p_code,$code])->pluck('name','code')->toArray();
                $form->p_name = $area[$p_code];
                $form->name = $area[$code];
                $form->city = $form->p_name.$form->name;
                $username = $form->username;
                $password = $form->password;
                if($form->isCreating()){
                    $exit = Administrator::query()->where("username",$username)->exists();
                    if ($exit){
                        return $form->response()->error("此账号已存在!");
                    }
                    $admin = new Administrator();
                    $admin->username = $username;
                    $admin->name = $form->city;
                    $admin->password = Hash::make($password);
                    $res = $admin->save();
                    if ($res){
                        $form->admin_id = $admin->id;
                    }
                }
                if($form->isEditing()){
                    $exit = Administrator::query()->where("id","<>",$form->admin_id)->where("username",$username)->exists();
                    if ($exit){
                        return $form->response()->error("此账号已存在!");
                    }
                    $admin = Administrator::query()->where("id",$form->admin_id)->first();
                    $admin->username = $username;
                    $admin->name = $form->city;
                    if ($password){
                        $admin->password = Hash::make($password);
                    }
                    $admin->save();
                }
                $form->deleteInput('username');
                $form->deleteInput('password');
            });
        });
    }
}
